﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using log4net;

namespace suirui.ZhuMu.Middlewares
{
    public class TraceIdMiddleware
    {
        private readonly RequestDelegate _next;
        private static readonly ILog log = LogManager.GetLogger(typeof(GlobalExceptionMildd));

        public TraceIdMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            string token = context.Request.Headers["t"];

            var traceid = string.Empty;
            if (context.Request.Headers.TryGetValue("zm-traceid", out var zmTraceId))
            {
                traceid = zmTraceId.ToString();
            }
            if (string.IsNullOrEmpty(traceid))
            {
                traceid = Guid.NewGuid().ToString();
                context.Request.Headers.Add("zm-traceid", traceid);
            }
            log.Debug(new { traceid = traceid, Path = context.Request.Path, token = token });
            await _next.Invoke(context);
        }
    }
    public static class TraceIdMiddlewareExtensions
    {
        public static IApplicationBuilder UseTraceId(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<TraceIdMiddleware>();
        }
    }
}
